package com.zlm.readWrite;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: 郑
 * ReadWriteLock 读写锁 可以多个线程读，只能一个线程写
 */
public class ReadWriteDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        //写入
        for (int i = 0; i < 10; i++) {
            final String temp = String.valueOf(i);
            new Thread(() -> {
                myCache.put(temp,temp);
            }).start();
        }
        //读取
        for (int i = 0; i < 10; i++) {
            final String temp = String.valueOf(i);
            new Thread(() -> {
                myCache.get(temp);
            }).start();
        }
    }
}

class MyCache{
    private volatile Map<String,Object> map = new HashMap<>();
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    //写入
    public void put(String key,Object value){
        reentrantReadWriteLock.writeLock().lock();//加写锁
        try {
            System.out.println(Thread.currentThread().getName() + "写入");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName() + "写入");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reentrantReadWriteLock.writeLock().unlock();//释放写锁
        }
    }
    //读取
    public void get(String key){
        reentrantReadWriteLock.readLock().lock();//加读锁
        try {
            System.out.println(Thread.currentThread().getName() + "读取");
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "=>读取"+o);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reentrantReadWriteLock.readLock().unlock();//释放锁
        }
    }
}
